package com.zhang.chatcenter.common.interceptor;

import com.zhang.infrastructure.model.principal.KingHoodUser;
import com.zhang.infrastructure.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 000095133
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        String username = request.getHeader("username");
        String issuer = request.getHeader("issuer");

        if(Objects.isNull(userId)){
            return true;
        }

        KingHoodUser user = new KingHoodUser();
        user.setId(Long.valueOf(userId));
        user.setUsername(username);
        user.setIssuer(issuer);
        UserUtil.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) {
        // Do nothing.
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {
        //清除上下文缓存
        UserUtil.remove();
    }
}